package com.yirui.serialcomm.core;

import com.fazecast.jSerialComm.SerialPort;
import com.yirui.serialcomm.core.domain.Port;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Dujie
 * @create 2025/8/5
 * @since 1.0.0
 */
public class PortListUtil {
    public static List list() {
        SerialPort[] ports = SerialPort.getCommPorts();
        List portList = new ArrayList();
        for (SerialPort port : ports) {

            portList.add(toMap(port));
        }
        return portList;
    }

    private static Port toMap(SerialPort port) {
        Port port1 = new Port();
        port1.setName(port.getSystemPortName());
        port1.setPath(port.getSystemPortPath());
        port1.setBaudRate(port.getBaudRate());
        port1.setReadBufferSize(port.getDeviceReadBufferSize());
        port1.setWriteBufferSize(port.getDeviceWriteBufferSize());
        port1.setWriteTimeout(port.getWriteTimeout());
        port1.setReadTimeout(port.getReadTimeout());
        // 设置硬件流控（RTS/CTS）
//        serialPort.setFlowControl(
//                SerialPort.FLOW_CONTROL_RTS_ENABLED |
//                        SerialPort.FLOW_CONTROL_CTS_ENABLED
//        );

        // 或者设置软件流控（XON/XOFF）
        // serialPort.setFlowControl(
        //     SerialPort.FLOW_CONTROL_XONXOFF_IN_ENABLED |
        //     SerialPort.FLOW_CONTROL_XONXOFF_OUT_ENABLED
        // );

        port1.setFlowControl(port.getFlowControlSettings());
        return port1;
    }
}
